package com.zxt.user.security.handle;

import com.alibaba.fastjson.JSON;
import com.zxt.bean.Result;
import com.zxt.bean.ResultCode;
import com.zxt.utils.ServletUtil;
import com.zxt.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;

/**
 * 认证失败处理类 返回未授权
 */
@Configuration
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {

    private static final long serialVersionUID = 1L;

    @Value("${token.header}")
    private String tokenHeader;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) {
        String token = request.getHeader(tokenHeader);
        if (StringUtils.isBlank(token)) {
            ServletUtil.renderString(response, JSON.toJSONString(Result.newError(ResultCode.NO_LOGGED_IN)));
        } else {
            ServletUtil.renderString(response, JSON.toJSONString(Result.newError(ResultCode.SESSION_INVALID_ERROR)));
        }
    }

}
